package cloud.hedou.abp.auth

import cloud.hedou.abp.identity.RemoteIdentityService
import cloud.hedou.abp.webcore.UnauthorizedException
import net.bytebuddy.implementation.bytecode.Throw
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.core.convert.converter.Converter
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.security.access.AuthorizationServiceException
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.oauth2.core.OAuth2AuthenticationException
import org.springframework.security.oauth2.core.OAuth2Error
import org.springframework.web.client.HttpClientErrorException
import org.springframework.web.client.HttpStatusCodeException
import retrofit2.HttpException

class AbpGrantedAuthoritiesConverter(
    private val remoteIdentityService: RemoteIdentityService
) : Converter<Jwt, Collection<GrantedAuthority>> {

    override fun convert(source: Jwt): Collection<GrantedAuthority> {
        return try {
            remoteIdentityService
                .getGrantedAuthorities(source.tokenValue)
                .map(::SimpleGrantedAuthority)
        } catch (throwable: Throwable) {
            throw OAuth2AuthenticationException(OAuth2Error("401"), throwable)
        }
    }

}